using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
using System.Net.NetworkInformation;
using TMPro;

public class Taxi : MonoBehaviour
{
    [SerializeField] private Customer Customer;
    [SerializeField] private ParticleSystem CoinEffect;
    [SerializeField] private TextMeshProUGUI TxtAddScore;
    private bool _isTakeCustomer = false;
    private int _nextCustomer = 0;
    private int _takeCustomers = 0;
    private Rigidbody _rigidbody;

    private void Awake()
    {
        _rigidbody = GetComponent<Rigidbody>();
    }

    private void Update()
    {
        TxtAddScore.transform.rotation = Quaternion.LookRotation(TxtAddScore.transform.position - Camera.main.transform.position);
    }

    private void Start()
    {
        Customer.gameObject.SetActive(false);
        _isTakeCustomer = false;
        _nextCustomer = UnityEngine.Random.Range(0, 2);
        TxtAddScore.gameObject.SetActive(false);
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Enemy")) {
            LevelMgr.Instance.State = GameState.Die;
            Vector3 pos = other.transform.position;
            Vector3 lpos = transform.InverseTransformPoint(pos);
            if (Mathf.Abs(lpos.z) >= Mathf.Abs(lpos.x))
            {
                other.transform.GetComponent<Rigidbody>().AddForce((other.transform.position - transform.position).normalized*2, ForceMode.Impulse);
                StartCoroutine(DelayStopCar(other.transform.GetComponent<Rigidbody>()));
            }
            else {
                _rigidbody.AddForce((transform.position - other.transform.position).normalized*2, ForceMode.Impulse);
                StartCoroutine(DelayStopCar(_rigidbody));
            }
        }
        StartArea start = other.GetComponent<StartArea>();
        if (start) {
            string msg = TextMsg.RandAskTaxi();
            EventMgr.EvtShowTalk.Invoke(msg, _nextCustomer);
            return;
        }
        EndArea end = other.GetComponent<EndArea>();
        if (end)
        {
            LevelMgr.Instance.State = GameState.Over;
            return;
        }
        House house = other.GetComponent<House>();
        if (house)
        {
            LevelMgr.Instance.State = GameState.Stop;
            _rigidbody.velocity = Vector3.zero;
            StopCustomerMove(other.transform.position);
            return;
        }
    }

    private IEnumerator DelayStopCar(Rigidbody rg) {
        yield return new WaitForSeconds(2.0f);
        rg.velocity = Vector3.zero;
        rg.angularVelocity = Vector3.zero;
    }

    private void StopCustomerMove(Vector3 housePos) {
        Vector3 pos = transform.InverseTransformPoint(housePos);
        bool isLeft = pos.x < 0;
        if (!_isTakeCustomer)
        {
            Vector3 posStart = isLeft ? new Vector3(-0.5f, 0, 0) : new Vector3(0.5f, 0, 0);
            Customer.SetCustomer(_nextCustomer);
            Vector3 posEnd = isLeft ? new Vector3(-0.2f, 0, 0) : new Vector3(0.2f, 0, 0);
            Customer.gameObject.SetActive(false);
            Customer.transform.localEulerAngles = isLeft ? new Vector3(0, 90, 0) : new Vector3(0, -90, 0);
            Customer.transform.localPosition = posStart;
            Sequence sequence = DOTween.Sequence();
            sequence.AppendInterval(1);
            sequence.AppendCallback(() =>
            {
                Customer.gameObject.SetActive(true);
            });
            sequence.Append(Customer.transform.DOLocalMove(posEnd, 1));
            sequence.OnComplete(() =>
            {
                Customer.gameObject.SetActive(false);
                string msg = TextMsg.RandSpeedTaxi();
                EventMgr.EvtShowTalk.Invoke(msg, _nextCustomer);
            });
            _isTakeCustomer = true;
        }
        else {
            _takeCustomers += 1;
            Customer.SetCustomer(_nextCustomer);
            Vector3 posStart = isLeft ? new Vector3(-0.2f, 0, 0) : new Vector3(0.2f, 0, 0);
            Vector3 posEnd = isLeft ? new Vector3(-0.5f, 0, 0) : new Vector3(0.5f, 0, 0);
            Customer.gameObject.SetActive(false);
            Customer.transform.localEulerAngles = isLeft ? new Vector3(0, -90, 0) : new Vector3(0, 90, 0);
            Customer.transform.localPosition = posStart;
            Sequence sequence = DOTween.Sequence();
            sequence.AppendInterval(1);
            sequence.AppendCallback(() =>
            {
                Customer.gameObject.SetActive(true);
            });
            sequence.Append(Customer.transform.DOLocalMove(posEnd, 1));
            sequence.OnComplete(() =>
            {
                Customer.gameObject.SetActive(false);
                _nextCustomer = UnityEngine.Random.Range(0, 2);
                if (_takeCustomers < LevelMgr.Instance.CustomerNumber) {
                    StartCoroutine(DelayTalk());
                }
            });
            _isTakeCustomer = false;
            CoinEffect.Play();
            StartCoroutine(PlayTxtScoreAni());
        }
    }

    private IEnumerator PlayTxtScoreAni() {
        yield return new WaitForSeconds(0.5f);
        TxtAddScore.gameObject.SetActive(true);
        TxtAddScore.rectTransform.anchoredPosition = new Vector2(0, 32);
        TxtAddScore.transform.localScale = Vector3.one;
        Sequence sequence = DOTween.Sequence();
        sequence.Append(TxtAddScore.rectTransform.DOAnchorPos(new Vector2(0, 64), 0.8f));
        sequence.Append(TxtAddScore.transform.DOScale(0, 0.2f));
        sequence.AppendCallback(()=> {
            TxtAddScore.gameObject.SetActive(false);
        });
    }

    private IEnumerator DelayTalk() {
        yield return new WaitForSeconds(Random.Range(0.5f, 0.8f));
        string msg = TextMsg.RandAskTaxi();
        EventMgr.EvtShowTalk.Invoke(msg, _nextCustomer);
    }
}
